﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Reporting.WebForms;
using System.Data;
using Runda.CMS.Bll;
using Runda.CMS.Common.Entity;
using Runda.CMS.Common.Utility;
using System.Text;
using Telerik.Web.UI;

namespace Runda.CMS.Portal.Report
{
    public partial class SalesRpt_Z2 : BasePage
    {
        public string SortString
        {
            get
            {
                if (ViewState["SortString"] == null)
                {
                    ViewState["SortString"] = "customername";
                }

                return ViewState["SortString"].ToString();
            }
            set { ViewState["SortString"] = value; }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                for (int i = 2012; i <= 2015; i++)
                {
                    ddlBudgetYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                DataTable dt = new BudgetBll().Companylist(base.CurrentUserID.ToString());
                ddlCompany.DataSource = dt;
                ddlCompany.DataTextField = "Departmentname";
                ddlCompany.DataValueField = "Departmentname";
                ddlCompany.DataBind();
                ddlCompany.Items.Add(new ListItem("--不限--", "0"));
                ddlCompany.SelectedValue = "0";


                if (ddlCompany.SelectedValue != "0")
                {
                    dt = new BudgetBll().Departmentlist(base.CurrentUserID.ToString(), ddlCompany.SelectedValue.ToString());

                    ddlDept.DataSource = dt;
                    ddlDept.DataTextField = "Departmentname";
                    ddlDept.DataValueField = "Departmentname";
                    ddlDept.DataBind();
                    ddlDept.Items.Add(new ListItem("--不限--", "0"));
                    ddlDept.SelectedValue = "0";
                }
                BindGrid(1);
                Calculate();
                LoadRadTree("");
            }
        }

        private void LoadRadTree(string categoryCode)
        {
            string categoryGUID = "";
            //List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode"); 
            DataTable dt = null;
            CtrtInstrumentCategoryBll bll = new CtrtInstrumentCategoryBll();
            dt = bll.GetInstrumentCategory("");//  and SUBSTRING(categorycode,1,2) in('01', '02')


            RadTreeView RadTreeProdType = RadComboBox_ProdType.Items[0].FindControl("RadTreeView_ProdType") as RadTreeView;
            //HtmlInputHidden Hidden_ProdTypeID = Page.FindControl("Text1") as HtmlInputHidden;
            //HtmlInputText txtSelectType = Page.FindControl("txt_SelectType") as HtmlInputText;
            if (RadTreeProdType != null)
            {
                RadTreeProdType.DataFieldID = "categoryGUID";
                RadTreeProdType.DataTextField = "categoryName";
                RadTreeProdType.DataValueField = "categoryGUID";
                RadTreeProdType.DataFieldParentID = "parentGUID";
                RadTreeProdType.DataSource = dt;
                RadTreeProdType.DataBind();
            }
            if (categoryCode != "")
            {
                Text1.Value = categoryCode;
                List<CtrtInstrumentCategoryEntity> categoryEntitys = new CtrtInstrumentCategoryBll().GetAll<CtrtInstrumentCategoryEntity>(" and parentGUID is null", "Order By categoryCode");

                if (categoryEntitys != null && categoryEntitys.Count > 0)
                {
                    categoryGUID = categoryEntitys[0].categoryCode;
                }

                if (categoryGUID != "")
                {
                    txt_SelectType.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;

                    RadComboBox_ProdType.SelectedItem.Value = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    RadComboBox_ProdType.SelectedItem.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                    RadComboBox_ProdType.Text = RadTreeProdType.FindNodeByValue(categoryGUID).Text;
                }
            }

        }

        protected void btnQuery_Click(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        protected void gridAccessoryList_ItemDataBound(object sender, Telerik.WebControls.GridItemEventArgs e)
        {

        }

        protected void AspNetPager1_PageChanged(object sender, EventArgs e)
        {
            BindGrid(AspNetPager1.CurrentPageIndex);
            Calculate();
        }

        private void BindGrid(int pageindex)
        {
            string sb = getWhereClause();

            int RecordCount = 0;
            DataTable dt = new BillBll().SaleBillsStat1(sb, SortString, AspNetPager1.PageSize, pageindex, out RecordCount);


            AspNetPager1.RecordCount = RecordCount;
            gridAccessoryList.DataSource = dt;
            gridAccessoryList.DataBind();
        }

        protected void gridAccessoryList_SortCommand(object source, Telerik.WebControls.GridSortCommandEventArgs e)
        {
            string OrderBy = e.SortExpression + " " + (e.NewSortOrder == Telerik.WebControls.GridSortOrder.Ascending ? "asc" : "desc");
            SortString = OrderBy;
            BindGrid(1);
            Calculate();
            

        }

        private string getWhereClause()
        {
            StringBuilder sb = new StringBuilder();

            //if (base.CurrentUserEntity.UserName == "郭海涛"
            //    || base.CurrentUserEntity.UserName == "史莹"
            //    || base.CurrentUserEntity.UserName == "王静"
            //    || base.CurrentUserEntity.UserName == "顾悦"
            //    || base.CurrentUserEntity.UserName == "宋欣"
            //    || base.CurrentUserEntity.UserName == "徐雪峰"
            //    || base.CurrentUserEntity.UserName == "胡日成"
            //    || base.CurrentUserEntity.UserName == "崔丽丽"
            //    || base.CurrentUserEntity.UserName == "官俊"
            //    || base.CurrentUserEntity.UserName == "李娜"
            //    || base.CurrentUserEntity.UserName == "张佳锦"
            //    )
            //{
            //    if (ddlStatPath1.SelectedValue == "1")
            //    {
            //        sb.Append(" and ([billUnit] in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("')))");
            //    }
            //    else
            //    { sb.Append(" and ([BudgetUnit] in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("')))"); }
            //}
            //else
            //{
                if (ddlStatPath1.SelectedValue == "1")
                {
                    sb.Append(" and ((billUnit in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
                    sb.Append(" and cCategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where categoryGUID in(select categoryGUID from Cms_sys_UserProductCategory where UserID ='").Append(base.CurrentUserID.ToString()).Append("')))");
                    //sb.Append(" and (billUnit in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
                    //sb.Append(" or cCategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where PM='").Append(base.CurrentUserEntity.UserName.ToString()).Append("')");
                    sb.Append(" or sales ='").Append(base.CurrentUserEntity.UserName.ToString()).Append("'");
                    sb.Append(" or sales in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("')))");
                }
                else
                {
                    sb.Append(" and ((BudgetUnit in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
                    sb.Append(" and cCategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where categoryGUID in(select categoryGUID from Cms_sys_UserProductCategory where UserID ='").Append(base.CurrentUserID.ToString()).Append("')))");
                    //sb.Append(" and (BudgetUnit in(").Append("select DepartmentName from cms_sys_Department where iscompany = 1 and DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("'))");
                    //sb.Append(" or cCategoryCode in(").Append("select categoryCode from Cms_Ctrt_InstrumentCategory where PM='").Append(base.CurrentUserEntity.UserName.ToString()).Append("')");
                    sb.Append(" or sales ='").Append(base.CurrentUserEntity.UserName.ToString()).Append("'");
                    sb.Append(" or sales in(").Append("select username from vw_sysUser where DepartmentID in(select DepartmentID from Cms_Sys_UserDepartment_DataRight where userid ='").Append(base.CurrentUserID.ToString()).Append("')))");
                }
                
            //}

            if (ddlBudgetYear.SelectedValue != string.Empty)
            {
                sb.Append(" and datepart(year,[dDate])  = ").Append(ddlBudgetYear.SelectedValue);
            }

            if (ddlStatPath2.SelectedValue == "1")
            { sb.Append(" and cCusCode in(select customerCode from cms_Bg_InnerCustomer)"); }
            else if (ddlStatPath2.SelectedValue == "2")
            { sb.Append(" and cCusCode not in(select customerCode from cms_Bg_InnerCustomer)"); }

            if (ddlCompany.SelectedValue != "0" && ddlStatPath1.SelectedValue=="1")
            {
                sb.Append(" and BillUnit='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }

            if (ddlCompany.SelectedValue != "0" && ddlStatPath1.SelectedValue == "2")
            {
                sb.Append(" and BudgetUnit='").Append(ddlCompany.SelectedValue.ToString()).Append("'");
            }

            if (txtCustomerName.Text.Trim() != "")
            {
                sb.Append(" and CustomerName like '%").Append(txtCustomerName.Text.Trim()).Append("%'");
            }

            string categoryCode="";
            SystemBll bll = new SystemBll();
            if (Text1.Value != "")
            {
                Guid ID = new Guid(Text1.Value);
                CtrtInstrumentCategoryEntity instrmentEntity = bll.Get<CtrtInstrumentCategoryEntity>(ID);
                if (instrmentEntity != null)
                {
                    categoryCode = instrmentEntity.categoryCode;
                }
            }
            if (categoryCode != "") { sb.Append(" and categorycode like '").Append(categoryCode).Append("%'"); }

            if (ddlDept.SelectedValue != "0" && ddlDept.SelectedValue!="")
            {
                sb.Append(" and DepartmentName = '").Append(ddlDept.SelectedValue).Append("'");
            }

            if (txtSales.Text.Trim() != "")
            {
                sb.Append(" and sales like '").Append(txtSales.Text.Trim()).Append("%'"); 
            }
            return sb.ToString();
        }

       
        
        private void Calculate()
        {
            string sb = getWhereClause();
            BillBll bll = new BillBll();
            DataTable dt = bll.CalcSaleBillsAmount1(sb);

            if (dt != null && dt.Rows.Count > 0)
            {
                hfsumTotalAmount.Value = string.Format("{0:N}", dt.Rows[0]["TotalAmount"]);
                hfsumm01iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m01iNatSum"]);
                hfsumm02iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m02iNatSum"]);
                hfsumm03iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m03iNatSum"]);
                hfsumm04iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m04iNatSum"]);
                hfsumm05iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m05iNatSum"]);
                hfsumm06iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m06iNatSum"]); ;
                hfsumm07iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m07iNatSum"]);
                hfsumm08iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m08iNatSum"]);
                hfsumm09iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m09iNatSum"]);
                hfsumm10iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m10iNatSum"]);
                hfsumm11iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m11iNatSum"]); ;
                hfsumm12iNatSum.Value = string.Format("{0:N}", dt.Rows[0]["m12iNatSum"]);
                hfsumm01Cost.Value = string.Format("{0:N}", dt.Rows[0]["m01Cost"]);
                hfsumm02Cost.Value = string.Format("{0:N}", dt.Rows[0]["m02Cost"]);
                hfsumm03Cost.Value = string.Format("{0:N}", dt.Rows[0]["m03Cost"]);
                hfsumm04Cost.Value = string.Format("{0:N}", dt.Rows[0]["m04Cost"]);
                hfsumm05Cost.Value = string.Format("{0:N}", dt.Rows[0]["m05Cost"]);
                hfsumm06Cost.Value = string.Format("{0:N}", dt.Rows[0]["m06Cost"]); ;
                hfsumm07Cost.Value = string.Format("{0:N}", dt.Rows[0]["m07Cost"]);
                hfsumm08Cost.Value = string.Format("{0:N}", dt.Rows[0]["m08Cost"]);
                hfsumm09Cost.Value = string.Format("{0:N}", dt.Rows[0]["m09Cost"]);
                hfsumm10Cost.Value = string.Format("{0:N}", dt.Rows[0]["m10Cost"]);
                hfsumm11Cost.Value = string.Format("{0:N}", dt.Rows[0]["m11Cost"]); ;
                hfsumm12Cost.Value = string.Format("{0:N}", dt.Rows[0]["m12Cost"]);
                hfsumTotalCost.Value = string.Format("{0:N}", dt.Rows[0]["TotalCost"]);

                hfsumm01Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m01iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m01Cost"]));
                hfsumm02Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m02iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m02Cost"]));
                hfsumm03Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m03iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m03Cost"]));
                hfsumm04Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m04iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m04Cost"]));
                hfsumm05Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m05iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m05Cost"]));
                hfsumm06Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m06iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m06Cost"]));
                hfsumm07Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m07iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m07Cost"]));
                hfsumm08Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m08iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m08Cost"]));
                hfsumm09Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m09iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m09Cost"]));
                hfsumm10Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m10iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m10Cost"]));
                hfsumm11Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m11iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m11Cost"]));
                hfsumm12Revenue.Value = string.Format("{0:N}", Convert.ToDecimal(dt.Rows[0]["m12iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m12Cost"]));
                hfsumTotalRevenue.Value = string.Format("{0:N}",Convert.ToDecimal(dt.Rows[0]["TotalAmount"]) - Convert.ToDecimal(dt.Rows[0]["TotalCost"]));

                if (Convert.ToDecimal(dt.Rows[0]["m01iNatSum"]) != 0)
                { hfsumm01RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m01iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m01Cost"])) / Convert.ToDecimal(dt.Rows[0]["m01iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m02iNatSum"]) != 0)
                { hfsumm02RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m02iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m02Cost"])) / Convert.ToDecimal(dt.Rows[0]["m02iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m03iNatSum"]) != 0)
                { hfsumm03RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m03iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m03Cost"])) / Convert.ToDecimal(dt.Rows[0]["m03iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m04iNatSum"]) != 0)
                { hfsumm04RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m04iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m04Cost"])) / Convert.ToDecimal(dt.Rows[0]["m04iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m05iNatSum"]) != 0)
                { hfsumm05RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m05iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m05Cost"])) / Convert.ToDecimal(dt.Rows[0]["m05iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m06iNatSum"]) != 0)
                { hfsumm06RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m06iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m06Cost"])) / Convert.ToDecimal(dt.Rows[0]["m06iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m07iNatSum"]) != 0)
                { hfsumm07RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m07iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m07Cost"])) / Convert.ToDecimal(dt.Rows[0]["m07iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m08iNatSum"]) != 0)
                { hfsumm08RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m08iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m08Cost"])) / Convert.ToDecimal(dt.Rows[0]["m08iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m09iNatSum"]) != 0)
                { hfsumm09RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m09iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m09Cost"])) / Convert.ToDecimal(dt.Rows[0]["m09iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m10iNatSum"]) != 0)
                { hfsumm10RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m10iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m10Cost"])) / Convert.ToDecimal(dt.Rows[0]["m10iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m11iNatSum"]) != 0)
                { hfsumm11RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m11iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m11Cost"])) / Convert.ToDecimal(dt.Rows[0]["m11iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["m12iNatSum"]) != 0)
                { hfsumm12RevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["m12iNatSum"]) - Convert.ToDecimal(dt.Rows[0]["m12Cost"])) / Convert.ToDecimal(dt.Rows[0]["m12iNatSum"])); }
                if (Convert.ToDecimal(dt.Rows[0]["TotalAmount"]) != 0)
                { hfsumTotalRevenueRate.Value = string.Format("{0:p}", (Convert.ToDecimal(dt.Rows[0]["TotalAmount"]) - Convert.ToDecimal(dt.Rows[0]["TotalCost"])) / Convert.ToDecimal(dt.Rows[0]["TotalAmount"])); }



            }
            else
            {
                hfsumTotalAmount.Value = "0";
                hfsumm01iNatSum.Value = "0";
                hfsumm02iNatSum.Value = "0";
                hfsumm03iNatSum.Value = "0";
                hfsumm04iNatSum.Value = "0";
                hfsumm05iNatSum.Value = "0";
                hfsumm06iNatSum.Value = "0";
                hfsumm07iNatSum.Value = "0";
                hfsumm08iNatSum.Value = "0";
                hfsumm09iNatSum.Value = "0";
                hfsumm10iNatSum.Value = "0";
                hfsumm11iNatSum.Value = "0";
                hfsumm12iNatSum.Value = "0";
            }
        }

        protected void btnExportExcel_Click(object sender, EventArgs e)
        {
            string sb = getWhereClause();
            BillBll bll = new BillBll();

            DataTable dt = bll.ExportSaleBillsStat1(sb);

            Export.Export2Excel(dt, "销售明细统计", Page.Response);

        }

        protected void ddlCompany_SelectedIndexChanged(object sender, EventArgs e)
        {
            ddlDept.Items.Clear();
            DataTable dt = new BudgetBll().Departmentlist(base.CurrentUserID.ToString(), ddlCompany.SelectedValue.ToString());

            ddlDept.DataSource = dt;
            ddlDept.DataTextField = "Departmentname";
            ddlDept.DataValueField = "Departmentname";
            ddlDept.DataBind();
            ddlDept.Items.Add(new ListItem("--不限--", "0"));
            ddlDept.SelectedValue = "0";
        }

    }
}
